package com.fantastic.service.zjs.impl;

import com.fantastic.common.exception.RegisterException;
import com.fantastic.common.exception.enums.RespStatusInfo;
import com.fantastic.mapper.zjs.AccountMapper;
import com.fantastic.mapper.zjs.UserMapper;
import com.fantastic.model.pojo.zjs.Account;
import com.fantastic.model.pojo.zjs.User;
import com.fantastic.service.zjs.RegisService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author: rxx
 * @since: 2024/6/14 10:05
 * @description:  账号注册实现
 */
@Service
public class RegisServiceImpl implements RegisService {

    @Resource
    private AccountMapper accountMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 注册账号
     * 注册后便要添加默认的客户端用户信息
     * 两种情况：
     * 1、员工账号由后台分配。（有员工id）
     * 2、普通用户账号自行中注册。（无员工id）
     * 用户信息id外键  由后端自动生成。
     * 账号密码注册 | | 手机号验证码注册
     * @param account 账号对象
     * @return 返回受影响行数
     */
    @Override
    @Transactional
    public Integer regis(Account account) {
        //注册信息校验
        regisInNull(account);
        //设置用户的默认信息
        User user = new User();
        user.setUserName(account.getAccount() != null && account.getAccount() != "" ? account.getAccount() : account.getPhone());
        user.setUserIntegral(0);
        //执行添加用户信息，拿到自增的主键，拿到用户信息id
        Integer userId = userMapper.insertUser(user);
        if (userId != null) {
            account.setUserId(userId);
        }
        //设置默认时间为注册时间
        account.setRegisDate(LocalDateTime.now());
        //设置默认账号状态
        account.setAccountStatus(1);
        //设置账号默认储蓄
        account.setAccountStored(new BigDecimal(0));
        return accountMapper.regisAccount(account);
    }


    /**
     * 校验注册信息是否合法
     *
     * @param account
     */
    public void regisInNull(Account account) {
        //判断账号密码或是手机号是否为空
        if (accountIsNull(account)) {
            return;
        }
        //抛出注册异常
        throw new RegisterException(RespStatusInfo.REGIS_ERROR);
    }
    /**
     * 判断账号信息，账号密码不为空或是手机号不为空
     *
     * @param account
     * @return
     */
    public boolean accountIsNull(Account account) {
        if ((account.getAccount() != null && account.getAccount() != ""
                && account.getPwd() != null && account.getPwd() != "")
                || (account.getPhone() != null && account.getPhone() != "")) {
            return true;
        }
        return false;
    }

}
